package edu.nf.relaxenjoy.common.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scripting.support.ResourceScriptSource;

/**
 * @author zhu
 * @date 2024-11-26
 */
@Configuration
public class RedisConfigure {

    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("127.0.0.1", 6379);
        redisStandaloneConfiguration.setDatabase(0);
        redisStandaloneConfiguration.setPassword(RedisPassword.of("redis"));
        return new LettuceConnectionFactory(redisStandaloneConfiguration);
    }
    /**
     * 自定义RedisTemplate，使用Jackson作为RedisTemplate的序列化器
     * @return 创建一个RedisTemplate该模板用于执行Redis的各种操作。
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        //创建RedisTemplate的实例
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //需要连接工厂来初始化template
        template.setConnectionFactory(lettuceConnectionFactory());
        //装配序列化器
        //key使用字符串的序列化器（StringRedisSerializer）
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        template.setKeySerializer(keySerializer);
        template.setHashKeySerializer(keySerializer);
        //value使用Jackson序列化器(GenericJackson2JsonRedisSerializer)
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        template.setValueSerializer(valueSerializer);
        template.setHashValueSerializer(valueSerializer);
        return template;
    }

    /**
     * 装配 RedisScript，用于执行 Lua 脚本
     * @return
     */
    @Bean
    public RedisScript<Long> redisScript() {
        // 创建RedisScript并指定lua脚本文件位置
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/stock.lua")));
        // 设置返回类型
        redisScript.setResultType(Long.class);
        return redisScript;
    }
}
